import { Table, Tag, Typography, Space, Card, Row, Col, Statistic, Input, Button, Select, Spin, Modal, Form, message, Tabs, Upload } from '@/utils/antd-imports';
import { CheckOutlined, CloseOutlined, SearchOutlined, TeamOutlined, EditOutlined, PlusOutlined, CalendarOutlined, ReloadOutlined, UploadOutlined, FileExcelOutlined, DownloadOutlined } from '@/utils/icons';
import React, { useState, useEffect } from 'react';
import { dynamicImportApi } from '@/api/dynamicImportApi';
import { exportToExcel } from '@/utils/excelExport';














import DatePicker from 'antd/es/date-picker';



import moment from 'moment';
import AttendanceTable from './AttendanceTable';
import OutputValueManagement from './OutputValueManagement';
import { contractPersonnelApi } from '@/api/contractPersonnelApi';

const { Title, Text } = Typography;
const { Option } = Select;
const { TabPane } = Tabs;

const ProjectMembers = ({ 
  subProjectsData = [], 
  projectCode = '', 
  loading = false 
}) => {
  const [searchText, setSearchText] = useState('');
  const [activeTab, setActiveTab] = useState('active');
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [addModalVisible, setAddModalVisible] = useState(false);
  const [currentMember, setCurrentMember] = useState(null);
  const [form] = Form.useForm();
  const [memberSearchText, setMemberSearchText] = useState('');
  const [selectedPerson, setSelectedPerson] = useState(null);
  const [searchResults, setSearchResults] = useState([]);
  const [outputValueModalVisible, setOutputValueModalVisible] = useState(false);
  const [currentOutputMember, setCurrentOutputMember] = useState(null);
  const [outputForm] = Form.useForm();
  const [membersData, setMembersData] = useState([]);
  const [fetchLoading, setFetchLoading] = useState(false);
  const [batchImportVisible, setBatchImportVisible] = useState(false);
  const [batchImportLoading, setBatchImportLoading] = useState(false);

  // 处理批量导入按钮点击
  const handleBatchImport = () => {
    setBatchImportVisible(true);
  };

  // 处理上传Excel文件（合同人员）
  const handleExcelUpload = async (file) => {
    setBatchImportLoading(true);
    try {
      const response = await dynamicImportApi.importContractPersonnel(file);
      
      if (response.code === 200) {
        message.success('批量导入成功');
        setBatchImportVisible(false);
        // 重新加载数据
        fetchContractPersonnel();
      } else {
        message.error(response.message || '批量导入失败');
      }
    } catch (error) {
      console.error('批量导入失败:', error);
      message.error('批量导入失败');
    } finally {
      setBatchImportLoading(false);
    }
    return false; // 阻止默认上传行为
  };

  // 从后端API获取合同人员数据
  useEffect(() => {
    if (projectCode) {
      fetchContractPersonnel();
    }
  }, [projectCode]);

  const fetchContractPersonnel = async () => {
    setFetchLoading(true);
    try {
      const response = await contractPersonnelApi.getPersonnelByProjectCode(projectCode);
      if (response.code === 200 && response.data) {
        // 转换后端数据格式为前端需要的格式
        const transformedData = response.data.map((person, index) => {
          // 映射单价类型
          const priceTypeMap = {
            'hour': '时',
            'day': '日',
            'month': '月'
          };
          
          return {
            id: person.id || index,
            subProjectId: null,
            subProjectName: person.department || '未分配部门',
            name: person.personnelName,
            startDate: person.startDate || '未设置',
            endDate: person.endDate || '未设置',
            price: person.unitPrice || 0,
            priceType: priceTypeMap[person.priceType] || person.priceType || '时',
            type: person.personnelType || '未分类',
            contactPerson: person.team || '未设置',
            lastProjectEndDate: '未设置',
            status: person.status === 'active' ? '正常' : '已离项'
          };
        });
        setMembersData(transformedData);
      } else {
        message.error('获取成员数据失败：' + (response.message || '未知错误'));
        setMembersData([]);
      }
    } catch (error) {
      console.error('获取成员数据失败：', error);
      message.error('获取成员数据失败，请检查网络连接');
      setMembersData([]);
    } finally {
      setFetchLoading(false);
    }
  };

  // 计算统计指标
  const calculateStats = (data) => {
    const total = data.length;
    const active = data.filter(m => m.status === '正常').length;
    const inactive = data.filter(m => m.status === '已离项').length;
    const avgPrice = data.reduce((sum, m) => sum + m.price, 0) / total || 0;
    
    const typeStats = {
      '公司自由人': data.filter(m => m.type === '公司自由人').length,
      '正式员工': data.filter(m => m.type === '正式员工').length,
      '外协人员': data.filter(m => m.type === '外协人员').length,
      '临时工': data.filter(m => m.type === '临时工').length
    };
    
    return {
      total,
      active,
      inactive,
      avgPrice,
      typeStats
    };
  };

  // 筛选数据
  const filteredData = membersData.filter(member => {
    const matchesSearch = member.subProjectName.includes(searchText) || 
                         member.name.includes(searchText);
    const matchesStatus = activeTab === 'all' || 
                         (activeTab === 'active' && member.status === '正常') || 
                         (activeTab === 'inactive' && member.status === '已离项');
    return matchesSearch && matchesStatus;
  });

  const stats = calculateStats(filteredData);

  // 处理编辑操作
  const handleEdit = (record) => {
    setCurrentMember(record);
    form.setFieldsValue({
      ...record,
      startDate: moment(record.startDate, 'YYYY.MM.DD'),
      endDate: moment(record.endDate, 'YYYY.MM.DD')
    });
    setEditModalVisible(true);
  };

  // 保存编辑
  const handleEditSubmit = () => {
    form.validateFields().then(values => {
      const updatedMember = {
        ...values,
        startDate: values.startDate.format('YYYY.MM.DD'),
        endDate: values.endDate.format('YYYY.MM.DD')
      };
      
      // 这里应该是调用API更新数据
      console.log('更新成员信息:', updatedMember);
      message.success('成员信息更新成功');
      setEditModalVisible(false);
    });
  };

  // 处理添加成员
  const handleAddMember = () => {
    form.validateFields().then(values => {
      const newMember = {
        ...values,
        name: selectedPerson.name,
        startDate: values.startDate.format('YYYY.MM.DD'),
        endDate: values.endDate.format('YYYY.MM.DD'),
        id: `new-${Date.now()}`,
        status: '正常',
        subProjectName: values.subProjectName
      };
      
      // 这里应该是调用API添加新成员
      console.log('添加新成员:', newMember);
      message.success('成员添加成功');
      setAddModalVisible(false);
      form.resetFields();
      setSelectedPerson(null);
    });
  };

  // 搜索人员库
  const handleSearchPersonnel = () => {
    const results = mockPersonnelLibrary.filter(person => 
      person.name.includes(memberSearchText) || 
      person.position.includes(memberSearchText) ||
      person.department.includes(memberSearchText)
    );
    setSearchResults(results);
  };

  // 处理产值按钮点击
  const handleOutputValue = (record) => {
    setCurrentOutputMember(record);
    outputForm.setFieldsValue({
      employeeId: record.id,
      employeeName: record.name,
      employeeType: record.type,
      projectName: record.subProjectName
    });
    setOutputValueModalVisible(true);
  };

  // 导出成员数据
  const handleExportMembers = () => {
    const dataToExport = filteredData;
    if (!dataToExport || dataToExport.length === 0) {
      message.warning('没有数据可导出');
      return;
    }
    
    try {
      const filename = `成员管理_${new Date().getTime()}.xlsx`;
      exportToExcel(dataToExport, memberColumns, filename);
      message.success('成员数据导出成功');
    } catch (error) {
      console.error('导出失败:', error);
      message.error('导出失败，请重试');
    }
  };

  // 提交产值表单
  const handleOutputValueSubmit = () => {
    outputForm.validateFields().then(values => {
      console.log('产值数据:', values);
      message.success('产值记录创建成功');
      setOutputValueModalVisible(false);
      outputForm.resetFields();
    });
  };

  // 成员表格列定义
  const memberColumns = [
    {
      title: '子项目名称',
      dataIndex: 'subProjectName',
      key: 'subProjectName',
      width: 200,
      render: (text) => <Text strong>{text}</Text>
    },
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
      width: 100
    },
    {
      title: '开始时间',
      dataIndex: 'startDate',
      key: 'startDate',
      width: 120
    },
    {
      title: '结束时间',
      dataIndex: 'endDate',
      key: 'endDate',
      width: 120
    },
    {
      title: '单价(元)',
      dataIndex: 'price',
      key: 'price',
      width: 120,
      render: (price) => price ? `${price}` : '-'
    },
    {
      title: '单价类型',
      dataIndex: 'priceType',
      key: 'priceType',
      width: 100,
      render: (text) => text || '-'
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      width: 120,
      render: (type) => {
        const colors = {
          '公司自由人': 'blue',
          '正式员工': 'green',
          '外协人员': 'orange',
          '临时工': 'red'
        };
        return (
          <Tag color={colors[type]}>
            {type}
          </Tag>
        );
      }
    },
    {
      title: '对接人',
      dataIndex: 'contactPerson',
      key: 'contactPerson',
      width: 120
    },
    {
      title: '上一个项目结束时间',
      dataIndex: 'lastProjectEndDate',
      key: 'lastProjectEndDate',
      width: 150
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status) => (
        status === '正常' ? 
        <Tag icon={<CheckOutlined />} color="success">正常</Tag> : 
        <Tag icon={<CloseOutlined />} color="error">已离项</Tag>
      )
    },
    {
      title: '操作',
      key: 'action',
      width: 150,
      render: (_, record) => (
        <Space>
          <Button 
            type="link" 
            icon={<EditOutlined />} 
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Button 
            type="link" 
            onClick={() => handleOutputValue(record)}
          >
            产值
          </Button>
        </Space>
      )
    }
  ];

  // 共用表单组件
  const MemberForm = ({ isEdit = false }) => (
    <Form form={form} layout="vertical">
      {!isEdit && (
        <>
          <Row gutter={16}>
            <Col span={24}>
              <Form.Item
                label="搜索人员"
                rules={[{ required: true, message: '请搜索并选择人员' }]}
              >
                <Space>
                  <Input
                    placeholder="输入人员姓名、职位或部门搜索"
                    value={memberSearchText}
                    onChange={(e) => setMemberSearchText(e.target.value)}
                    style={{ width: 300 }}
                  />
                  <Button 
                    type="primary" 
                    onClick={handleSearchPersonnel}
                  >
                    搜索
                  </Button>
                </Space>
              </Form.Item>
              
              {searchResults.length > 0 && (
                <div style={{ marginTop: 10 }}>
                  <Text strong>搜索结果：</Text>
                  <div style={{ marginTop: 8 }}>
                    {searchResults.map(person => (
                      <Button
                        key={person.id}
                        type={selectedPerson?.id === person.id ? 'primary' : 'default'}
                        onClick={() => setSelectedPerson(person)}
                        style={{ marginRight: 8, marginBottom: 8 }}
                      >
                        {person.name} ({person.position}, {person.department})
                      </Button>
                    ))}
                  </div>
                </div>
              )}
              
              {selectedPerson && (
                <div style={{ marginTop: 10 }}>
                  <Text strong>已选择人员：</Text>
                  <Tag color="blue" style={{ marginLeft: 8 }}>
                    {selectedPerson.name} ({selectedPerson.position}, {selectedPerson.department})
                  </Tag>
                </div>
              )}
            </Col>
          </Row>
        </>
      )}
      
      <Row gutter={16}>
        <Col span={24}>
          <Form.Item
            label="子项目名称"
            name="subProjectName"
            rules={[{ required: true, message: '请输入子项目名称' }]}
          >
            <Input placeholder="请输入子项目名称" />
          </Form.Item>
        </Col>
      </Row>
      
      <Row gutter={16}>
        <Col span={12}>
          <Form.Item
            label="开始时间"
            name="startDate"
            rules={[{ required: true, message: '请选择开始时间' }]}
          >
            <DatePicker style={{ width: '100%' }} format="YYYY-MM-DD" />
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item
            label="结束时间"
            name="endDate"
            rules={[{ required: true, message: '请选择结束时间' }]}
          >
            <DatePicker style={{ width: '100%' }} format="YYYY-MM-DD" />
          </Form.Item>
        </Col>
      </Row>
      
      <Row gutter={16}>
        <Col span={12}>
          <Form.Item
            label="单价"
            name="price"
            rules={[{ required: true, message: '请输入单价' }]}
          >
            <Input type="number" addonAfter="元" />
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item
            label="单价类型"
            name="priceType"
            rules={[{ required: true, message: '请选择单价类型' }]}
          >
            <Select>
              <Option value="小时">小时</Option>
              <Option value="日">日</Option>
              <Option value="月">月</Option>
            </Select>
          </Form.Item>
        </Col>
      </Row>
      
      <Row gutter={16}>
        <Col span={12}>
          <Form.Item
            label="类型"
            name="type"
            rules={[{ required: true, message: '请选择类型' }]}
          >
            <Select>
              <Option value="公司自由人">公司自由人</Option>
              <Option value="正式员工">正式员工</Option>
              <Option value="外协人员">外协人员</Option>
              <Option value="临时工">临时工</Option>
            </Select>
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item
            label="对接人"
            name="contactPerson"
            rules={[{ required: true, message: '请输入对接人' }]}
          >
            <Input />
          </Form.Item>
        </Col>
      </Row>
      
      <Row gutter={16}>
        <Col span={24}>
          <Form.Item
            label="上一个项目结束时间"
            name="lastProjectEndDate"
            rules={[{ required: true, message: '请输入上一个项目结束时间' }]}
          >
            <Input />
          </Form.Item>
        </Col>
      </Row>
    </Form>
  );

  return (
    <div style={{ padding: '24px 24px' }}>
      {/* 标题 */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24 }}>
        <Title level={3} style={{ margin: 0 }}>
          项目成员管理 - {projectCode || '未指定项目'}
        </Title>
        {projectCode && (
          <Button 
            icon={<ReloadOutlined />}
            onClick={fetchContractPersonnel}
            loading={fetchLoading}
          >
            刷新数据
          </Button>
        )}
      </div>
      
      {/* 主Tabs导航 */}
      <Tabs type="card" defaultActiveKey="members" style={{ marginBottom: 24 }}>
        <TabPane tab={<span><TeamOutlined />成员管理</span>} key="members">
          {fetchLoading ? (
            <div style={{ textAlign: 'center', padding: '50px 0' }}>
              <Spin size="large" />
            </div>
          ) : (
            <>
              {/* 统计指标卡片 */}
              <Row gutter={16} style={{ marginBottom: 16 }}>
                <Col span={6}>
                  <Card>
                    <Statistic
                      title="总成员数"
                      value={stats.total}
                      prefix={<TeamOutlined />}
                    />
                  </Card>
                </Col>
                <Col span={6}>
                  <Card>
                    <Statistic
                      title="在项成员"
                      value={stats.active}
                      valueStyle={{ color: '#52c41a' }}
                    />
                  </Card>
                </Col>
                <Col span={6}>
                  <Card>
                    <Statistic
                      title="已离项成员"
                      value={stats.inactive}
                      valueStyle={{ color: '#ff4d4f' }}
                    />
                  </Card>
                </Col>
                <Col span={6}>
                  <Card>
                    <Statistic
                      title="平均单价(元)"
                      value={stats.avgPrice.toFixed(2)}
                      prefix="¥"
                    />
                  </Card>
                </Col>
              </Row>
              
              {/* 类型分布统计 */}
              <Row gutter={16} style={{ marginBottom: 16 }}>
                {Object.entries(stats.typeStats).map(([type, count]) => (
                  <Col span={6} key={type}>
                    <Card>
                      <Statistic
                        title={`${type}数量`}
                        value={count}
                      />
                    </Card>
                  </Col>
                ))}
              </Row>
              
              {/* 筛选区域 */}
              <Card style={{ marginBottom: 16 }}>
                <Space>
                  <Input
                    placeholder="按子项目名称或成员姓名搜索"
                    prefix={<SearchOutlined />}
                    value={searchText}
                    onChange={(e) => setSearchText(e.target.value)}
                    style={{ width: 250 }}
                  />
                  
                  <Button 
                    onClick={() => {
                      setSearchText('');
                    }}
                  >
                    重置筛选
                  </Button>
                  
                  <Button 
                    type="primary" 
                    icon={<PlusOutlined />}
                    onClick={() => {
                      setAddModalVisible(true);
                      setSelectedPerson(null);
                      setSearchResults([]);
                      form.resetFields();
                    }}
                  >
                    添加成员
                  </Button>
                  
                  <Button 
                    type="default" 
                    icon={<UploadOutlined />}
                    onClick={handleBatchImport}
                  >
                    批量添加
                  </Button>
                  <Button 
                    type="default" 
                    icon={<DownloadOutlined />}
                    onClick={handleExportMembers}
                  >
                    导出数据
                  </Button>
                </Space>
              </Card>
                              {/* 状态Tabs */}
                <Tabs 
                type="card"
                  activeKey={activeTab}
                  onChange={setActiveTab}
                  style={{ marginTop: 16 }}
                >
                  <TabPane tab="在项成员" key="active" />
                  <TabPane tab="已离项成员" key="inactive" />
                  <TabPane tab="全部成员" key="all" />
                </Tabs>
              {/* 成员表格 */}
              <Table
                columns={memberColumns}
                dataSource={filteredData}
                rowKey="id"
                pagination={{ pageSize: 10 }}
                scroll={{ x: 1650 }}
                bordered
                size="middle"
                locale={{
                  emptyText: filteredData.length === 0 && searchText ? 
                    `没有找到与"${searchText}"相关的成员` : 
                    '暂无成员数据'
                }}
              />
              
              {/* 编辑成员对话框 */}
              <Modal
                title="编辑成员信息"
                visible={editModalVisible}
                onOk={handleEditSubmit}
                onCancel={() => setEditModalVisible(false)}
                width={700}
                destroyOnClose
              >
                <MemberForm isEdit />
              </Modal>
              
              {/* 添加成员对话框 */}
              <Modal
                title="添加成员"
                visible={addModalVisible}
                onOk={handleAddMember}
                onCancel={() => {
                  setAddModalVisible(false);
                  setSelectedPerson(null);
                  setSearchResults([]);
                  form.resetFields();
                }}
                width={700}
                destroyOnClose
              >
                <MemberForm />
              </Modal>

              {/* 产值管理对话框 */}
              <Modal
                title="产值管理"
                visible={outputValueModalVisible}
                onOk={handleOutputValueSubmit}
                onCancel={() => {
                  setOutputValueModalVisible(false);
                  outputForm.resetFields();
                }}
                width={600}
                destroyOnClose
              >
                <Form form={outputForm} layout="vertical">
                  <Row gutter={16}>
                    <Col span={12}>
                      <Form.Item
                        label="序号"
                        name="serialNumber"
                        rules={[{ required: true, message: '请输入序号' }]}
                      >
                        <Input placeholder="请输入序号" />
                      </Form.Item>
                    </Col>
                    <Col span={12}>
                      <Form.Item
                        label="工号"
                        name="employeeId"
                        rules={[{ required: true, message: '请输入工号' }]}
                      >
                        <Input placeholder="请输入工号" disabled />
                      </Form.Item>
                    </Col>
                  </Row>
                  
                  <Row gutter={16}>
                    <Col span={12}>
                      <Form.Item
                        label="姓名"
                        name="employeeName"
                        rules={[{ required: true, message: '请输入姓名' }]}
                      >
                        <Input placeholder="请输入姓名" disabled />
                      </Form.Item>
                    </Col>
                    <Col span={12}>
                      <Form.Item
                        label="员工类型"
                        name="employeeType"
                        rules={[{ required: true, message: '请选择员工类型' }]}
                      >
                        <Select disabled>
                          <Option value="公司自由人">公司自由人</Option>
                          <Option value="正式员工">正式员工</Option>
                          <Option value="外协人员">外协人员</Option>
                          <Option value="临时工">临时工</Option>
                        </Select>
                      </Form.Item>
                    </Col>
                  </Row>
                  
                  <Row gutter={16}>
                    <Col span={24}>
                      <Form.Item
                        label="项目名称"
                        name="projectName"
                        rules={[{ required: true, message: '请输入项目名称' }]}
                      >
                        <Input placeholder="请输入项目名称" disabled />
                      </Form.Item>
                    </Col>
                  </Row>
                  
                  <Row gutter={16}>
                    <Col span={24}>
                      <Form.Item
                        label="是否有订单"
                        name="hasOrder"
                        rules={[{ required: true, message: '请选择是否有订单' }]}
                      >
                        <Select placeholder="请选择是否有订单">
                          <Option value="是">是</Option>
                          <Option value="否">否</Option>
                        </Select>
                      </Form.Item>
                    </Col>
                  </Row>
                  
                  <Row gutter={16}>
                    <Col span={24}>
                      <Form.Item
                        label="扣减"
                        name="deduction"
                        rules={[{ required: true, message: '请输入扣减' }]}
                      >
                        <Input placeholder="请输入扣减" />
                      </Form.Item>
                    </Col>
                  </Row>
                </Form>
              </Modal>

              {/* 批量导入对话框 */}
              <Modal
                title="批量导入合同人员"
                visible={batchImportVisible}
                onCancel={() => {
                  setBatchImportVisible(false);
                }}
                footer={null}
                width={600}
                destroyOnClose
              >
                <Upload
                  accept=".xlsx,.xls"
                  beforeUpload={handleExcelUpload}
                  showUploadList={false}
                  disabled={batchImportLoading}
                >
                  <Button 
                    type="primary" 
                    icon={<UploadOutlined />}
                    loading={batchImportLoading}
                    block
                    size="large"
                  >
                    {batchImportLoading ? '导入中...' : '选择Excel文件上传'}
                  </Button>
                </Upload>
                
                <div style={{ marginTop: 16, padding: '12px', background: '#f5f5f5', borderRadius: '4px' }}>
                  <Typography.Text type="secondary">
                    <FileExcelOutlined style={{ marginRight: 4 }} />
                    请上传包含合同人员信息的Excel文件
                  </Typography.Text>
                  <br />
                  <Typography.Text type="secondary" style={{ fontSize: '12px', marginTop: 8, display: 'block' }}>
                    支持的文件格式：.xlsx, .xls
                  </Typography.Text>
                </div>
              </Modal>
            </>
          )}
        </TabPane>
        <TabPane tab={<span><CalendarOutlined />考勤管理</span>} key="attendance">
          <AttendanceTable projectCode={projectCode} />
        </TabPane>
        <TabPane tab={<span><TeamOutlined />产值管理</span>} key="output">
          <OutputValueManagement />
        </TabPane>
      </Tabs>
    </div>
  );
};

export default ProjectMembers;